package com.newlink.building.userinfo.activity

import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.view.Gravity
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.constant.Base_Constant
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.utils.Base_CommonUtils
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.widget.CustomMessageDialog
import com.newlink.building.userinfo.Module_UserInfo_BtOpenDoorService2
import com.newlink.building.userinfo.Module_UserInfo_BtOpenDoorService2.Companion.SERVICE_START
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.databinding.ActivityAuthManageBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_AuthManagePresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_AuthManageContract

/**
 * @Author: Jake
 * @Date: 2023-09-12
 * @Description:
 */
class Module_UserInfo_AuthManageActivityNL : NL_BaseMvpActivity<Module_UserInfo_AuthManageContract.View, Module_UserInfo_AuthManageContract.Presenter>(),
    Module_UserInfo_AuthManageContract.View, View.OnClickListener {

    companion object {
        private val BLUETOOTH_PERMISSIONS_S = arrayOf(
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )

        private val BLUETOOTH_PERMISSIONS = arrayOf(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        )
    }

    private val items by lazy {
        resources.getStringArray(R.array.bt_shake_level)
    }

    override fun createPresenter(): Module_UserInfo_AuthManageContract.Presenter = Module_UserInfo_AuthManagePresenter()

//    override fun attachLayoutRes(): Int = R.layout.activity_auth_manage

    private lateinit var mBinding: ActivityAuthManageBinding
    private var mBroadcastReceiver: BtRequestBroadcastReceiver? = null
    private lateinit var enableBluetoothLauncher: ActivityResultLauncher<Intent>
    override fun attachLayoutRes(): View {
        mBinding = ActivityAuthManageBinding.inflate(layoutInflater)
        return mBinding.root
    }

    // supervisor
    @SuppressLint("WrongConstant")
    override fun initData() {
        mBroadcastReceiver = BtRequestBroadcastReceiver()


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            ContextCompat.registerReceiver(
                this@Module_UserInfo_AuthManageActivityNL,
                mBroadcastReceiver,
                IntentFilter(Base_Constant.ACTION_REQUEST_BLE_PERMISSION),
                ContextCompat.RECEIVER_NOT_EXPORTED
            )
        } else {
            registerReceiver(
                mBroadcastReceiver,
                IntentFilter(Base_Constant.ACTION_REQUEST_BLE_PERMISSION)
            )
        }


//        enableBluetoothLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
//            if (result.resultCode == Activity.RESULT_OK) {
//                // 用户同意开启蓝牙
//                NLog.e("toggle bluetooth true")
//                startBleService()
//            } else {
//                // 用户拒绝开启蓝牙
//                useBluetooth = false
//                mBinding.authBtSwitch.isChecked = false
//            }
//        }
    }

    override fun initView() {
        super.initView()
        findViewById<TextView>(R.id.tv_title_bar_center).text =
            resources.getText(R.string.settings_auth)
        if (userInfoData.userCategory == 3) {
            mBinding.authLayoutCard.visibility = View.GONE
            mBinding.authLayoutFace.visibility = View.GONE
            mBinding.authCardDivider.visibility = View.GONE
        }

        mBinding.authLayoutPwd.setOnClickListener(this)
        mBinding.authLayoutCard.setOnClickListener(this)
        mBinding.authLayoutBluetooth.setOnClickListener(this)

        mBinding.authLayoutFace.setOnClickListener(this)
        mBinding.authBtSwitch.setOnCheckedChangeListener { _, isChecked ->
            NLog.e("[jake] .. auth_bt_switch isCheck: $isChecked")
            useBluetooth = isChecked
            mBinding.authLayoutBluetoothWay.visibility = if (isChecked) View.VISIBLE else View.GONE

            if (!isChecked) {
                switchBtOpenDoorService(false)
                return@setOnCheckedChangeListener
            }

            if (Base_CommonUtils.isServiceRunning(
                    this@Module_UserInfo_AuthManageActivityNL,
                    Module_UserInfo_BtOpenDoorService2::class.java.name
                )
            ) {
                return@setOnCheckedChangeListener
            }

            startBleService()

//            if (isBleEnable()) {
//
//            } else {
//                toggleBluetooth()
//            }

        }

//        mBinding.authBluetoothWaySpinner.setOnClickListener(this)

        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, items)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)

        mBinding.authBluetoothWaySpinner.adapter = adapter
        val defaultLevel = shakeLevel
        mBinding.authBluetoothWaySpinner.setSelection(defaultLevel)

        mBinding.authBluetoothWaySpinner.onItemSelectedListener =
            object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>,
                    view: View,
                    position: Int,
                    id: Long
                ) {
                    if (position == shakeLevel) {
                        return
                    }
                    NLog.e("jake ... Spinner Go........")
                    shakeLevel = position
                    val serviceIntent = Intent(applicationContext, Module_UserInfo_BtOpenDoorService2::class.java)
                    serviceIntent.action = Module_UserInfo_BtOpenDoorService2.SERVICE_UPDATE_SHAKE_LEVEL
                    this@Module_UserInfo_AuthManageActivityNL.startService(serviceIntent)
                }

                override fun onNothingSelected(parent: AdapterView<*>) {
                }
            }
    }

    private fun startBleService() {

        if (!isBleEnable()) {
            toggleBluetooth()
            mBinding.authBtSwitch.isChecked = false
            useBluetooth = false
            return
        }

        if (hasBluetoothPermissions()) {
            NLog.e("jake ... 我已经有了所有的权限了........")
            switchBtOpenDoorService(true)
            mBinding.authBtSwitch.isChecked = true
            useBluetooth = true
        } else {
            checkBluetoothPermission()
            mBinding.authBtSwitch.isChecked = false
            useBluetooth = false
//            initPermission()
        }
    }

    fun isBleEnable(): Boolean {
        val bluetoothAdapter = getBluetoothAdapter()
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled
    }

    private var bluetoothAdapter: BluetoothAdapter? = null
    private fun getBluetoothAdapter(): BluetoothAdapter? {
        if (bluetoothAdapter == null) {
            bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        }
        return bluetoothAdapter
    }

//    private lateinit var enableBluetoothLauncher: ActivityResultLauncher<Intent>
//    fun toggleBluetooth() {
//        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
//        enableBluetoothLauncher.launch(enableBtIntent)
//    }


    override fun onResume() {
        super.onResume()
        mBinding.authBtSwitch.isChecked = useBluetooth
        mBinding.authLayoutBluetoothWay.visibility = if (useBluetooth) View.VISIBLE else View.GONE
    }

    override fun showData() {
    }

    private fun hasBluetoothPermissions(): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            BLUETOOTH_PERMISSIONS_S.all {
                ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
            }
        } else {
            BLUETOOTH_PERMISSIONS.all {
                ContextCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
            }
        }

    }

    private var mPermissionList = ArrayList<String>()

    private fun initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 版本大于等于 Android12 时
            // 只包括蓝牙这部分的权限，其余的需要什么权限自己添加
            mPermissionList.add(Manifest.permission.BLUETOOTH_SCAN)
            mPermissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE)
            mPermissionList.add(Manifest.permission.BLUETOOTH_CONNECT)
        }
        // Android 版本小于 Android12 及以下版本
        mPermissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        mPermissionList.add(Manifest.permission.ACCESS_FINE_LOCATION)

        if (mPermissionList.size > 0) {
            ActivityCompat.requestPermissions(
                this@Module_UserInfo_AuthManageActivityNL,
                mPermissionList.toArray(arrayOfNulls<String>(0)),
                1001
            )
        }
    }


    override fun onClick(v: View?) {
        when (v) {
            mBinding.authLayoutPwd -> {
                startActivity(Intent(this@Module_UserInfo_AuthManageActivityNL, Module_UserInfo_AuthPasswordActivityNL::class.java))
            }

            mBinding.authLayoutCard -> {
                startActivity(Intent(this@Module_UserInfo_AuthManageActivityNL, Module_UserInfo_AuthCardAddActivityNL::class.java))
            }

//            mBinding.authLayoutBluetoothWay -> {
////                if (checkPermissions()) {
////                    NLog.e("jake ... 我已经有了所有的权限了........")
////                    switchBleOpenDoor()
////                } else {
////                    checkLocationPermission()
////                }
//            }

            mBinding.authLayoutFace -> {
                startActivity(Intent(this@Module_UserInfo_AuthManageActivityNL, Module_UserInfo_AuthFaceActivityNL::class.java))
            }
        }

    }


    private fun switchBtOpenDoorService(isOpen: Boolean) {
        Log.e("jake", "switchBtOpenDoorService $isOpen")
        if (isOpen) {
            startBtService()
        } else {
            stopBtService()
        }
    }

    private fun startBtService() {
        NLog.e("start BT service ")
//        val serviceIntent = Intent(applicationContext, BtOpenDoorService::class.java)
        val serviceIntent = Intent(applicationContext, Module_UserInfo_BtOpenDoorService2::class.java)
        serviceIntent.action = SERVICE_START
        this.startService(serviceIntent)
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            startForegroundService(serviceIntent)
//        } else {
//            this.startService(serviceIntent)
//        }
    }


    private fun stopBtService() {
//        val serviceIntent = Intent(applicationContext, BtOpenDoorService::class.java)
        val serviceIntent = Intent(applicationContext, Module_UserInfo_BtOpenDoorService2::class.java)
        this.stopService(serviceIntent)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        NLog.e("[jake] .. onRequestPermissionsResult  $requestCode , ${permissions[0]} , ${grantResults[0]}")
        if (requestCode == 1001) {
            if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                switchBtOpenDoorService(useBluetooth)
                mBinding.authBtSwitch.isChecked = true
                useBluetooth = true
            } else {

                NLog.e("[jake] .. Permission denied")
                useBluetooth = false
                mBinding.authBtSwitch.isChecked = false
//                showPermissionRationale()
//                checkBluetoothPermission()
                if (ActivityCompat.shouldShowRequestPermissionRationale(
                        this,
                        Manifest.permission.ACCESS_COARSE_LOCATION
                    )
                ) {
                    //拒绝
                    checkBluetoothPermission()
                } else {
                    openAppSettings()
                }

            }
        }

    }

    private fun showPermissionRationale() {
        val alertDialog = AlertDialog.Builder(this)
            .setMessage(getString(R.string.tips_go_setting_content))
            .setPositiveButton(getString(R.string.app_need_allow_display_over_go)) { _, _ ->
                openAppSettings()
            }
            .setNegativeButton(getString(R.string.cancel_dialog_custom), null)
            .create()

        alertDialog.show()

        alertDialog.window?.run {
            attributes = attributes.apply {
                width = (windowManager.defaultDisplay.width * 0.95).toInt()
                gravity = Gravity.CENTER
            }
        }
    }

    private fun openAppSettings() {
        val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
            data = Uri.fromParts("package", packageName, null)
        }
        startActivity(intent)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mBroadcastReceiver != null) {
            unregisterReceiver(mBroadcastReceiver!!)
            mBroadcastReceiver = null
        }
    }

    inner class BtRequestBroadcastReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (action.equals(Base_Constant.ACTION_REQUEST_BLE_PERMISSION)) {
                this@Module_UserInfo_AuthManageActivityNL.mBinding.authBtSwitch.isChecked = false
            }
        }
    }

    private fun checkBluetoothPermission() {
        val message = getString(
            R.string.common_permission_bluetooth_message,
            getString(R.string.common_permission_to_setting),
            getString(R.string.common_permission_location)
        )

        CustomMessageDialog(this).setTitle(getString(R.string.common_permission_title))
            .setMessage(message)

            .setNegativeButton(
                getString(R.string.cancel_dialog_custom)
            ) { dialog ->
                dialog.dismiss()
                showToast(getString(R.string.common_permission_cancel_alert))
            }
            .setPositiveButton(
                getString(R.string.common_permission_to_setting)
            ) { dialog ->
                initPermission()
                dialog.dismiss()
            }.show()
    }

    override fun onBluetoothEnabledResult(isEnabled: Boolean) {
        if (isEnabled) {
            startBleService()
        }
    }

}